﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using XChipTool.Enties;
using System.IO;
using XChip_Common;
using SerialPortHelperLib;
using System.IO.Ports;
using System.Threading;

namespace XChipTool
{
    public partial class XChip_SettingSecurity : DevExpress.XtraEditors.XtraForm
    {
        public delegate void SendEventBinSettingNewMsg(string msg);
        public event SendEventBinSettingNewMsg SendBinSetMsg;
        int currentXPosition;
        int currentYPosition;
        bool beginMove = false;

        private string GuidNo;
        private int Id = -1;
        private bincurrency_export BinModel;
        private bincurrencyManager Bincurrency_BLL;
        private bool osdcheck = false;
        private List<string> Pageslist;
        public SerialPort sPortTemp;
        private bool isRead = false;
        /// <summary>
        /// // -1 表示无选着  0 表示案件 1表示adc
        /// </summary>
        public int isPress_key;
        private string pollintStr;

        private List<BinChoiceData> listBin = new List<BinChoiceData>();
        public XChip_SettingSecurity()
        {
            InitializeComponent();
        }

        public XChip_SettingSecurity(bincurrency_export binmodel, bool Osdcheck, List<string> pageslist, SerialPort _sPortTemp, int _isPress_key = -1)
        {
            osdcheck = Osdcheck;
            Pageslist = pageslist;
            Id = binmodel.Id;
            GuidNo = binmodel.GuidId;
            BinModel = binmodel;
            isPress_key = _isPress_key;
            sPortTemp = _sPortTemp;
            //listBin = new List<BinChoiceData>();
            InitializeComponent();
        }

       
        #region 窗体关闭移动

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            //for (int i = 0; i < 48; i++)
            //{
            //    LookUpEdit settingPath = this.Controls.Find($"settingPath{i + 1}", true)[0] as LookUpEdit;
            //    LookUpEdit settingPath_tve = this.Controls.Find($"settingPath_tve{i + 1}", true)[0] as LookUpEdit;
            //    if (settingPath.Text !="请选择文件")
            //    {
            //        LookUpEdit settingPath_iq = this.Controls.Find($"settingPath_iq{i + 1}", true)[0] as LookUpEdit;
            //        LookUpEdit settingPath_sensor = this.Controls.Find($"settingPath_sensor{i + 1}", true)[0] as LookUpEdit;
            //        if (settingPath_iq.Text == "请选择"|| settingPath_tve.Text == "请选择"|| settingPath_sensor.Text == "请选择")
            //        {
            //            Control col = this.Controls.Find($"txtgroup{i + 1}", true)[0];
            //            XtraMessageBox.Show($"请导入{col.Text}文件");
            //            return;
            //        }

            //    }
            //    else if(settingPath_tve.Text != "请选择")
            //    {

            //    }

            //}

            if (isPress_key !=-1&&string.IsNullOrEmpty(pollintStr))
            {
                XtraMessageBox.Show("轮询未选择");
                return;
            }

            var model99 = Bincurrency_BLL.GetSingle(c => c.GuidId == GuidNo && c.SerialNo == 48 && c.BinId == 7);
            if (null == model99)
            {
                XtraMessageBox.Show("请导入common_setting");
                return;
            }
            var Tipslist = SettingToTve151.SetTips151.Where(c => c.Tips != null && c.Tips != "").ToList();
            //这里过滤出来没有导入setting和tve的制式
            Tipslist.RemoveAll(c => c.Setting.Count() == 0 && c.TveSetting.Count() == 0);
            var Nulllist = Tipslist.Where(c => c.Setting.Count() == 0 || c.TveSetting.Count() == 0).ToList();
            if (0 != Nulllist.Count())
            {
                string Nullstr = "缺少：";
                for (int i = 0; i < Nulllist.Count(); i++)
                {
                    Nullstr += Nulllist[i].Tips + "下";
                    if (0 == Nulllist[i].Setting.Count())
                    {
                        Nullstr += " Setting,";
                    }
                    if (0 == Nulllist[i].TveSetting.Count())
                    {
                        Nullstr += " TveSetting,";
                    }
                    if (0 == Nulllist[i].IqSetting.Count())
                    {
                        Nullstr += " IqSetting,";
                    }
                    if (0 == Nulllist[i].SensorSetting.Count())
                    {
                        Nullstr += " SensorSetting,";
                    }

                }
                XtraMessageBox.Show($"{Nullstr}");
                return;

            }
            //查找去重找出所有文件路径
            //var Tvesettinglist = Tipslist.SelectMany(c => c.TveSetting).Select(v => v.FilePath).Distinct().ToList();
            //var Iqsettinglist = Tipslist.SelectMany(c => c.IqSetting).Select(v => v.FilePath).Distinct().ToList();
            //var Sensorsettinglist = Tipslist.SelectMany(c => c.SensorSetting).Select(v => v.FilePath).Distinct().ToList();

            var Tvesettinglist = Tipslist.SelectMany(c => c.TveSetting).Distinct().ToList();
            var Iqsettinglist = Tipslist.SelectMany(c => c.IqSetting).Distinct().ToList();
            var Sensorsettinglist = Tipslist.SelectMany(c => c.SensorSetting).Distinct().ToList();
            List<LoadSetting> FileNamelist = new List<LoadSetting>();
            //setting文件加载至数据库
            uint tvetag = 0x32;
            uint iqtag = 0x52;
            uint sentag = 0x58;

            uint addrBase = 0x7e00;

            List<LoadSetting> loadList = new List<LoadSetting>();
            List<string> HexOutlist = new List<string>();
            List<string> nullloadlist = new List<string>();
            HexOutlist.Add("0xfffd,0x20,");
            HexOutlist.Add("0xfffe,0x00,");
            var tMode = VideoHelper.GetTransferMode();
            var vMode = VideoHelper.GetVideoMode();
            int osdmax = 0;
            //OSD下筛选出所有没有导入的制式Load赋值FF
            var nullload = SettingToTve151.SetTips151.Where(c => c.Tips != null && c.Tips != "" ).ToList();
            if (osdcheck)
            {
                for (int i = 0; i < nullload.Count(); i++)
                {
                    if (nullload[i].Setting.Count()== 0)
                    {
                        nullloadlist.Add("0x" + (0x7e00 + (int.Parse(nullload[i].SettingNo) - 1) * 3).ToString("X2") + ",0xFF,");
                    }
                }
            }
            
            if (osdcheck)
            {
                HexOutlist.Add("0x13a5,0x01,//[7:0]OSDVideoFoldEnable");
                HexOutlist.Add("0x13a8,0x01,//[7:0]Osd_Format_Smart_Adjust_Enable");
            }
            else
            {
                HexOutlist.Add("0x13a5,0x00,//[ 7: 0]OSDVideoFoldEnable");
                HexOutlist.Add("0x13a8,0x00,//[7:0]Osd_Format_Smart_Adjust_Enable");
            }
            for (int j = 0; j < Tipslist.Count; j++)
            {
                //如果没有SensorSetting则导入一个空的的SensorSetting
                if (0 == Tipslist[j].SensorSetting.Count)
                {
                    Tipslist[j].SensorSetting.Add(new SettingData
                    {
                        FileName = "sensor_setting_null.txt",
                        FilePath = Application.StartupPath + "\\Lib\\sensor_setting_null.txt",
                        IsChecked = true,
                        Tag = Tipslist[j].Setting[0].Tag,
                    }) ;
                }
                int settingno = Int32.Parse(Tipslist[j].SettingNo) - 1;
                if (osdmax < settingno)
                {
                    osdmax = settingno;
                }
                if (osdcheck)
                {
                    HexOutlist.Add(Tipslist[j].HexOut.Split(',')[0] + "," + Tipslist[j].VideoHex + ",//" + Tipslist[j].hexNote);
                }
                foreach (var setitem in Tipslist[j].Setting)
                {
                    if (setitem.IsChecked)
                    {
                        var setHex = tMode.Find(c => setitem.FileName.ToLower().Contains(c.Name.ToLower())).Hex.Replace("0x", "") + vMode.Find(c => setitem.FileName.ToLower().Contains(c.Name.ToLower())).Hex.Replace("0x", "");
                        BinSetting(setitem.FilePath, Tipslist[j].SettingNo.ToString(), Convert.ToUInt32(setHex, 16));
                        //BinSetting(setitem.FilePath, Tipslist[j].SettingNo.ToString());
                    }
                }

                for (int i = 0; i < Tipslist[j].TveSetting.Count(); i++)
                {
                    if (Tipslist[j].TveSetting[i].IsChecked)
                    {
                        if (!FileNamelist.Any(c => c.FileName.Contains(Tipslist[j].TveSetting[i].FileName)))
                        {
                            FileNamelist.Add(new LoadSetting { FileName = Tipslist[j].TveSetting[i].FileName, val = tvetag - 1 });
                            BinSetting(Tipslist[j].TveSetting[i].FilePath, tvetag.ToString());
                            loadList.Add(new LoadSetting { val = tvetag - 1, addr = addrBase + (uint)(settingno * 3), FileName = Tipslist[j].TveSetting[i].FileName });
                            tvetag++;
                        }
                        else
                        {
                            var loadFileName = FileNamelist.Find(c => c.FileName == Tipslist[j].TveSetting[i].FileName);
                            loadList.Add(new LoadSetting { val = loadFileName.val, addr = addrBase + (uint)(settingno * 3), FileName = loadFileName.FileName });
                        }

                    }
                }


                for (int i = 0; i < Tipslist[j].IqSetting.Count; i++)
                {
                    if (Tipslist[j].IqSetting[i].IsChecked)
                    {
                        if (!FileNamelist.Any(c => c.FileName.Contains(Tipslist[j].IqSetting[i].FileName)))
                        {
                            FileNamelist.Add(new LoadSetting { FileName = Tipslist[j].IqSetting[i].FileName, val = iqtag - 1 });
                            BinSetting(Tipslist[j].IqSetting[i].FilePath, iqtag.ToString());
                            loadList.Add(new LoadSetting { val = iqtag - 1, addr = addrBase + (uint)(settingno * 3) + 1, FileName = Tipslist[j].IqSetting[i].FileName });
                            iqtag++;
                        }
                        else
                        {
                            var loadFileName = FileNamelist.Find(c => c.FileName == Tipslist[j].IqSetting[i].FileName);
                            loadList.Add(new LoadSetting { val = loadFileName.val, addr = addrBase + (uint)(settingno * 3) + 1, FileName = loadFileName.FileName });
                        }

                    }
                }

                for (int i = 0; i < Tipslist[j].SensorSetting.Count; i++)
                {
                    if (Tipslist[j].SensorSetting[i].IsChecked)
                    {

                        if (!FileNamelist.Any(c => c.FileName.Contains(Tipslist[j].SensorSetting[i].FileName)) || Tipslist[j].SensorSetting[i].FileName == "sensor_setting_null.txt")
                        {
                            FileNamelist.Add(new LoadSetting { FileName = Tipslist[j].SensorSetting[i].FileName, val = sentag - 1 });
                            BinSetting(Tipslist[j].SensorSetting[i].FilePath, sentag.ToString());
                            loadList.Add(new LoadSetting { val = sentag - 1, addr = addrBase + (uint)(settingno * 3) + 2, FileName = Tipslist[j].SensorSetting[i].FileName });
                            sentag++;
                        }
                        else
                        {
                            var loadFileName = FileNamelist.Find(c => c.FileName == Tipslist[j].SensorSetting[i].FileName);
                            loadList.Add(new LoadSetting { val = loadFileName.val, addr = addrBase + (uint)(settingno * 3) + 2, FileName = loadFileName.FileName });
                        }

                    }
                }
            }
            for (int i = 0; i < loadList.Count(); i++)
            {
                if (i == 0)
                {
                    HexOutlist.Add("//SettingLoad Order");
                }
                HexOutlist.Add(loadList[i].note);
            }
            if (osdcheck)
            {
                HexOutlist.AddRange(nullloadlist);
            }
            if (Pageslist != null)
            {
                HexOutlist.Add("//OSD_Misc");
                HexOutlist.Add($"0x1435,0x{Pageslist[0]},");
                HexOutlist.Add($"0x142d,0x{Pageslist[1]},");
            }
            if (osdcheck)
            {
                HexOutlist.Add($"0x14b0,0x{(osdmax + 1).ToString("X2")},");
            }

            //添加轮询的内容
            HexOutlist.Add(pollintStr);
            //判断该路径下文件是否存在
            if (File.Exists(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_Setting.txt"))
            {
                //如果存在文件就删除
                File.Delete(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_Setting.txt");
            }
            File.AppendAllLines(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_Setting.txt", HexOutlist);


            //var CommonSettingFile = Copy_Files_For_Header_Patch_Tool(Application.StartupPath + "\\Lib\\xc151_setting\\XChipCommonSetting.txt", true, "", true, false);
            //model99.BinOutPath = CommonSettingFile;
            //model99.BinOutName = Path.GetFileName(CommonSettingFile);
            //model99.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model99.BinOutPath);
            //model99.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            //Bincurrency_BLL.Update(model99);

            BinSetting(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_Setting.txt", "128");
            if (null != SendBinSetMsg)
            {
                SendBinSetMsg("");
            }
            this.Close();
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            if (null != SendBinSetMsg)
            {
                SendBinSetMsg("");
            }
            DialogResult dr = DevExpress.XtraEditors.XtraMessageBox.Show($"选择YES保存后退出！ \r\n 选择NO直接退出！", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
            if (dr == DialogResult.No)
            {

                if (osdcheck)
                {
                    EmptySetTips151File();
                }
                else
                {
                    EmptySetTips151();

                }
               

                commonTxt.EditValue = null;
                commonTxt.ItemIndex = -1;
               
                this.Close();
            }
            else
            {


                simpleButton1_Click(null, null);
                //this.Close();
            }

            //if (null != SendBinSetMsg)
            //{
            //    SendBinSetMsg("");
            //}
        }

        private void panelControl1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                beginMove = true;
                currentXPosition = MousePosition.X;
                currentYPosition = MousePosition.Y;
            }
        }

        private void panelControl1_MouseMove(object sender, MouseEventArgs e)
        {
            if (beginMove)
            {
                this.Left += MousePosition.X - currentXPosition;
                this.Top += MousePosition.Y - currentYPosition;
                currentXPosition = MousePosition.X;
                currentYPosition = MousePosition.Y;
            }
        }

        private void panelControl1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                currentXPosition = 0;
                currentYPosition = 0;
                beginMove = false;
            }
        }




        #endregion


        /// <summary>
        /// 初始化加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void XChip_SettingSecurity_Load(object sender, EventArgs e)
        {
            if (null == Bincurrency_BLL) //初始化
            {
                Bincurrency_BLL = new bincurrencyManager();
            }
            //commonsetting赋值
            if (osdcheck)
            {
                labelControl194.Text = "安防";
            }
            else
            {
                labelControl194.Text = "行车";
            }
             ///这两个在未选择文件的时候都是不能编辑
            bianhaoLook.Enabled = false;
            btn_polling.Enabled = false;
            //清空下拉框数据源
            ClearLookUpEditDataSource();
            var list = Bincurrency_BLL.GetListToDefault(GuidNo);
            var model99 = list.Find(c => (c.BinId == 7 && c.SerialNo == 48) && c.BinInPath != null);
            if (model99 != null)
            {
                commonTxt.Properties.DataSource = new List<SettingData> { new SettingData { FilePath = model99.BinInPath, FileName = model99.BinInName } };
                commonTxt.ItemIndex = 0;
            }
            #region 除去commonsetting以外所有setting赋值
            var Tipslist = SettingToTve151.SetTips151.Where(c => c.Tips != null && c.Tips != "").ToList();
            //这里过滤出来没有导入setting和tve的制式
            Tipslist.RemoveAll(c => c.Setting.Count() == 0 && c.TveSetting.Count() == 0);
            for (int i = 0; i < Tipslist.Count(); i++)
            {
                LookUpEdit settingPath = this.Controls.Find($"settingPath{Tipslist[i].SettingNo}", true)[0] as LookUpEdit;
                LookUpEdit settingPath_iq = this.Controls.Find($"settingPath_iq{Tipslist[i].SettingNo}", true)[0] as LookUpEdit;
                LookUpEdit settingPath_tve = this.Controls.Find($"settingPath_tve{Tipslist[i].SettingNo}", true)[0] as LookUpEdit;
                LookUpEdit settingPath_sensor = this.Controls.Find($"settingPath_sensor{Tipslist[i].SettingNo}", true)[0] as LookUpEdit;

                if (0 != Tipslist[i].Setting.Count || 0 != Tipslist[i].TveSetting.Count)
                {
                    settingPath.Properties.DataSource = Tipslist[i].Setting.Where(c => c.IsChecked).ToList();
                    listBin.Add(new BinChoiceData() { tag = i, BinName = $"{ Tipslist[i].Setting.Find(c => c.IsChecked).PathName}", isShow = true ,Sort = i});
                    //刷新一下下拉框
                    settingPath.Properties.BeginUpdate();
                    settingPath.ItemIndex = 0;
                    if (null != Tipslist[i].IqSetting)
                    {
                        settingPath_iq.Properties.DataSource = Tipslist[i].IqSetting.Where(c => c.IsChecked).ToList();
                        settingPath_iq.Properties.BeginUpdate();
                        settingPath_iq.ItemIndex = 0;
                    }
                    if (null != Tipslist[i].TveSetting)
                    {
                        settingPath_tve.Properties.DataSource = Tipslist[i].TveSetting.Where(c => c.IsChecked).ToList();
                        settingPath_tve.Properties.BeginUpdate();
                        settingPath_tve.ItemIndex = 0;
                    }
                    if (null != Tipslist[i].SensorSetting && "sensor_setting_null.txt" != Tipslist[i].SensorSetting[0].FileName)
                    {
                        settingPath_sensor.Properties.DataSource = Tipslist[i].SensorSetting.Where(c => c.IsChecked).ToList();
                        settingPath_sensor.Properties.BeginUpdate();
                        settingPath_sensor.ItemIndex = 0;
                    }
                }
            }


            if (listBin.Count>0)
            {
                btn_polling.Enabled = true;
                bianhaoLook.Enabled = true;
                bianhaoLook.Properties.DataSource = listBin;
                bianhaoLook.ItemIndex = 0;
            }
            #endregion

            if (osdcheck)
            {
                Task.Run(() => {
                    this.Invoke((EventHandler)delegate {
                        for (int i = 0; i < 48; i++)
                        {

                            try
                            {
                                var colbtniq = this.Controls.Find($"iqbtn_all_{(i + 1).ToString().PadLeft(2, '0')}", true)[0];
                                colbtniq.Visible = false;
                                Control colbtntve = this.Controls.Find($"tvebtn_all_{(i + 1).ToString().PadLeft(2, '0')}", true)[0];
                                colbtntve.Visible = false;
                                Control col = this.Controls.Find($"txtgroup{i + 1}", true)[0];
                                if (!string.IsNullOrEmpty(SettingToTve151.SetTips151[i].Tips))
                                {
                                    col.Text = SettingToTve151.SetTips151[i].TransferName + SettingToTve151.SetTips151[i].VideoName + "_" + (int.Parse(SettingToTve151.SetTips151[i].SettingNo) - 1).ToString();
                                }
                                else
                                {
                                    col.Visible = false;
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                    });
                });
            }
            else
            {
                Task.Run(() => {
                    this.Invoke((EventHandler)delegate {
                        for (int i = 0; i < 48; i++)
                        {

                            try
                            {
                                //var t = $"iqbtn_all_{i.ToString().PadLeft(2, '0')}";
                                //iqbtn_all_01
                                var colbtniq = this.Controls.Find($"iqbtn_all_{(i+1).ToString().PadLeft(2, '0')}", true)[0];
                                colbtniq.Visible = false;
                                Control colbtntve = this.Controls.Find($"tvebtn_all_{(i + 1).ToString().PadLeft(2, '0')}", true)[0];
                                colbtntve.Visible = false;
                                Control col = this.Controls.Find($"txtgroup{i + 1}", true)[0];
                                col.Text = $"Setting{i}";

                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                    });
                });
            }
            btn_polling.Visible = !(isPress_key == -1);
        }
        #region 下拉框所有事件
        /// <summary>
        /// 文件路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void settingPath1_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var settingPath = sender as LookUpEdit;
            if (string.IsNullOrEmpty(settingPath.Text.ToString()) || settingPath.Text.ToString() == "请选择") return;

            //BinSetting(settingPath.Text.ToString(), settingPath.Tag.ToString());
            SetRefreshChecked(settingPath.Text.ToString(), int.Parse(settingPath.Tag.ToString()), "setting");
        }




        private void SetRefreshChecked(string _path, int tag, string type)
        {

            switch (type.ToLower())
            {
                case "setting":
                    {

                        foreach (var item in SettingToTve151.SetTips151[tag - 1].Setting)
                        {
                            item.Tag = tag;
                            if (item.FileName == _path)
                            {
                                item.IsChecked = true;
                            }
                            else
                            {
                                item.IsChecked = false;
                            }
                        }
                    }
                    break;
                case "tve":
                    {
                        foreach (var item in SettingToTve151.SetTips151[tag - 1].TveSetting)
                        {
                            item.Tag = tag;
                            if (item.FileName == _path)
                            {
                                item.IsChecked = true;
                            }
                            else
                            {
                                item.IsChecked = false;
                            }
                        }
                    }
                    break;
                case "iq":
                    {
                        //SettingToTve151.SetTips151[0].IqSetting[0].IsChecked = false;
                        foreach (var item in SettingToTve151.SetTips151[tag - 1].IqSetting)
                        {
                            item.Tag = tag;
                            if (item.FileName == _path)
                            {
                                item.IsChecked = true;
                            }
                            else
                            {
                                item.IsChecked = false;
                            }
                        }
                    }
                    break;
                case "sensor":
                    {
                        foreach (var item in SettingToTve151.SetTips151[tag - 1].SensorSetting)
                        {
                            item.Tag = tag;
                            if (item.FileName == _path)
                            {
                                item.IsChecked = true;
                            }
                            else
                            {
                                item.IsChecked = false;
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }



        private void BinSetting(string pathName, string tag, uint hex = 0x0)
        {
            //setting0~setting47   common_setting setting48 setting49~setting98
            var list = Bincurrency_BLL.GetList(c => c.GuidId == BinModel.GuidId && (c.BinId == 6 || c.BinId == 7 || c.BinId == 8 || c.BinId == 9) && c.SerialNo != 48);
            var modelMax = list.Max(c => c.SortOrder) == null ? 0 : list.Max(c => c.SortOrder);
            var tagTemp = (int.Parse(tag) - 1);
            //var modelT = SettingTo151_Help.SetTips151[tagTemp];
            uint settingHex = hex; //方便Bin去查找setting位置信息 当前更改后处于无用状态 所以注销
            //if (string.IsNullOrEmpty(modelT.TransferHex) || string.IsNullOrEmpty(modelT.VideoHex))
            //{
            //    settingHex = Convert.ToUInt32($"{tagTemp.ToString("X2")}000000", 16);
            //}
            //else
            //{
            //    settingHex = Convert.ToUInt32($"{tagTemp.ToString("X2")}00{modelT.TransferHex.Replace("0x", "")}{modelT.VideoHex.Replace("0x", "")}", 16);
            //}

            if (list.Exists(c => c.SerialNo == tagTemp))
            {
                var model = list.Find(c => c.SerialNo == tagTemp);
                model.BinInPath = pathName;
                model.BinInName = Path.GetFileName(pathName);
                var pathNameout = Copy_Files_For_Header_Patch_Tool(pathName, true, "", true, false, settingHex);
                model.BinOutName = Path.GetFileName(pathNameout);
                model.BinOutPath = pathNameout;
                model.SerialNo = tagTemp;
                model.FileStatus = 2;
                model.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model.BinOutPath);
                Bincurrency_BLL.Update(model);
            }
            else
            {
                bincurrency model = new bincurrency();
                model.GuidId = GuidNo;
                model.BinId = (tagTemp / 32) + 6;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                model.BinInPath = pathName;
                model.BinInName = Path.GetFileName(pathName);
                var pathNameout = Copy_Files_For_Header_Patch_Tool(pathName, true, "", true, false, settingHex);
                model.BinOutName = Path.GetFileName(pathNameout);
                model.BinOutPath = pathNameout;
                model.FileStatus = 2;
                model.SerialNo = tagTemp;
                //model.SortOrder = modelMax + 1;
                model.SortOrder = tagTemp;
                model.IsModified = 0;
                model.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model.BinOutPath);
                Bincurrency_BLL.Insert(model);
            }
        }
        /// <summary>
        /// 拷贝文件 //生成批处理文本//生成批处理文件//执行批处理文件//生成完成
        /// </summary>
        /// <param name="Inputfilepath">文本路径</param>
        /// <param name="Isflash">是flash版本还eeprom版本</param>
        /// <param name="eepromaddr">eeprom值</param>
        /// <param name="isSetting">区分是setting栏还是其他栏</param>
        public string Copy_Files_For_Header_Patch_Tool(string Inputfilepath, bool Isflash, string eepromaddr, bool isSetting, bool isHead, uint setHex = 0x0)
        {
            string strFileName = System.IO.Path.GetFileName(Inputfilepath); //获取文件名
            string strNewSavePath = Application.StartupPath + "\\Lib\\xc151_setting\\Flash_" + setHex.ToString("X2") + strFileName;
            //判断该路径下文件是否存在
            if (File.Exists(strNewSavePath))
            {
                //如果存在文件就删除
                File.Delete(strNewSavePath);
            }
            if (isHead)
            {
                Setting2FlashE2prom.FlashHeader2Flash(Inputfilepath, strNewSavePath);
            }
            else
            {
                //Setting2FlashE2prom.FlashSetting2Flash(Inputfilepath, strNewSavePath, 1, 0, 0);
                Setting2FlashE2prom.FlashSetting2Flash(Inputfilepath, strNewSavePath, 0, 0, 0, 0, 0, setHex);
            }

            return strNewSavePath;
        }



        /// <summary>
        /// Tve 文件路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void settingPath_tve1_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var settingPath = sender as LookUpEdit;
            if (string.IsNullOrEmpty(settingPath.Text.ToString()) || settingPath.Text.ToString() == "请选择") return;

            SetRefreshChecked(settingPath.Text.ToString(), int.Parse(settingPath.Tag.ToString()), "tve");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pathName"></param>
        /// <param name="tag"></param>
        private void BinTveSetting(string pathName, string tag)
        {
            //setting49~setting80  common_setting setting48
            var list = Bincurrency_BLL.GetList(c => c.GuidId == BinModel.GuidId && (c.BinId == 7 || c.BinId == 8) && c.SerialNo != 48);
        }
        /// <summary>
        /// IQ 文件路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void settingPath_iq1_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var settingPath = sender as LookUpEdit;
            if (string.IsNullOrEmpty(settingPath.Text.ToString()) || settingPath.Text.ToString() == "请选择") return;
            SetRefreshChecked(settingPath.Text.ToString(), int.Parse(settingPath.Tag.ToString()), "iq");
        }
        /// <summary>
        /// sensor 文件路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void settingPath_sensor1_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var settingPath = sender as LookUpEdit;
            if (string.IsNullOrEmpty(settingPath.Text.ToString()) || settingPath.Text.ToString() == "请选择") return;
            SetRefreshChecked(settingPath.Text.ToString(), int.Parse(settingPath.Tag.ToString()), "sensor");
        }
        #endregion

        #region 选择文件夹

        /// <summary>
        /// 处理选择文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectFolderButton_Click(object sender, EventArgs e)
        {
            ///这两个在未选择文件的时候都是不能编辑
            bianhaoLook.Enabled = false;
            btn_polling.Enabled = false;
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            dialog.SelectedPath = AppHelper.GetAppConfig("Folder_Road_Force_Setting");
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                //清空下拉框数据源
                ClearLookUpEditDataSource();
                EmptySetTips151();
                //清空 数据库Setting文件

                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 6 || c.BinId == 7 || c.BinId == 8 || c.BinId == 9);
                commonTxt.EditValue = null;
                commonTxt.ItemIndex = -1;
                string foldPath = dialog.SelectedPath;
                AppHelper.UpdateAppConfig("Folder_Road_Force_Setting", foldPath);
                AppHelper.UpdateAppConfig("Folder_BinSetting", foldPath);
                HandleLoadingFolder(foldPath);

                if (listBin.Count!=0)
                {
                    bianhaoLook.Properties.DataSource = listBin;
                    bianhaoLook.ItemIndex = 0;
                }
            }

            bianhaoLook.Enabled = true;
            btn_polling.Enabled = true;
        }


        private void HandleLoadingFolder(string path)
        {
            var filePaths = Directory.GetFiles(path, "*.txt").Concat(Directory.GetFiles(path, "*.c")).ToArray();
            listBin = new List<BinChoiceData>();
            List<SettingData> tlvList = new List<SettingData>();
            string nulltips = "";
            string nulldatapath = "";
            foreach (var item in filePaths)
            {
                if (Path.GetFileName(item).Contains(" "))
                {
                    continue;
                }
                if (item.IndexOf(".bak", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    continue;
                }
                tlvList.Add(new SettingData { FilePath = item, FileName = Path.GetFileName(item) });
            }
            
            //common 文件夹赋值
            var commonList = tlvList.Where(c => c.FileName.ToLower().Contains("common_setting")).ToList();
            if (commonList.Count() != 0)
            {
                commonTxt.Properties.DataSource = commonList;
                commonTxt.EditValue = commonList.Count() > 1 ? string.Empty : commonList.First().FilePath;
                commonTxt.ItemIndex = 0;
            }

            if (osdcheck)
            {
                for (int i = 0; i < SettingToTve151.SetTips151.Count(); i++)
                {
                    var TransferName = SettingToTve151.SetTips151[i].TransferName;
                    var VideoName = SettingToTve151.SetTips151[i].VideoName;
                    //if (VideoName.Contains("5M20")|| VideoName.Contains("5M12"))
                    //{

                    //}
                    if (null == VideoName || null == TransferName)
                    {
                        continue;
                    }
                    //listBin.Add(new BinChoiceData() { tag = i, BinName = $"{ SettingToTve151.SetTips151[i].Tips}", isShow = true });
                    if (null != SettingToTve151.SetTips151[i].Setting)
                    {
                        SettingToTve151.SetTips151[i].Setting = new List<SettingData>();
                        var aa = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("datapath") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        var t1 = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("tve") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        if (aa.Count == 0 || t1.Count == 0)
                        {
                            continue;
                        }
                        var copy = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("datapath") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        for (int z = 0; z < copy.Count(); z++)
                        {
                            SettingToTve151.SetTips151[i].Setting.Add(new SettingData { FilePath = copy[z].FilePath, FileName = copy[z].FileName });
                        }
                        //添加轮询需要的List文件


                        var t = tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("sensor") && c.PathName.ToLower().Contains(aa.Last().sensorName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].SensorSetting = new List<SettingData>();
                        copy = tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("sensor") && c.PathName.ToLower().Contains(aa.Last().sensorName.ToLower())).ToList();
                        if (TransferName.ToLower() == "cvbs")
                        {
                            switch (aa.Last().sensorName.ToLower())
                            {
                                case "720p60fps":
                                    copy.AddRange(tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("sensor") && c.FileName.ToLower().Contains("ntsc") && c.FileName.ToLower().Contains("720p")).ToList());
                                    break;
                                case "720p50fps":
                                    copy.AddRange(tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("sensor") && c.FileName.ToLower().Contains("pal") && c.FileName.ToLower().Contains("720p")).ToList());
                                    break;
                                case "960h60fps":
                                    copy.AddRange(tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("sensor") && c.FileName.ToLower().Contains("ntsc") && c.FileName.ToLower().Contains("960h")).ToList());
                                    break;
                                case "960h50fps":
                                    copy.AddRange(tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("sensor") && c.FileName.ToLower().Contains("pal") && c.FileName.ToLower().Contains("960h")).ToList());
                                    break;
                                default:
                                    break;
                            }
                        }
                        for (int z = 0; z < copy.Count(); z++)
                        {
                            SettingToTve151.SetTips151[i].SensorSetting.Add(new SettingData { FilePath = copy[z].FilePath, FileName = copy[z].FileName });
                        }
                        SettingToTve151.SetTips151[i].TveSetting = new List<SettingData>();
                        copy = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("tve") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        for (int z = 0; z < copy.Count(); z++)
                        {
                            SettingToTve151.SetTips151[i].TveSetting.Add(new SettingData { FilePath = copy[z].FilePath, FileName = copy[z].FileName });
                        }
                        SettingToTve151.SetTips151[i].IqSetting = new List<SettingData>();
                        //
                        copy = tlvList.Where(c => !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("iq_setting")).ToList();
                        for (int z = 0; z < copy.Count(); z++)
                        {
                            SettingToTve151.SetTips151[i].IqSetting.Add(new SettingData { FilePath = copy[z].FilePath, FileName = copy[z].FileName });
                        }
                    }
                    else
                    {
                        SettingToTve151.SetTips151[i].Setting = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("datapath") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].SensorSetting = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("sensor") && c.sensorName.ToLower().Contains(SettingToTve151.SetTips151[i].Setting.Last().sensorName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].TveSetting = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("tve") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].IqSetting = tlvList.Where(c => !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("iq_setting")).ToList();
                    }
                    listBin.Add(new BinChoiceData() { tag = i, BinName = $"{ SettingToTve151.SetTips151[i].Setting.Last().PathName}", isShow = true ,Sort = i});
                    try
                    {
                        LookUpEdit settingPath = this.Controls.Find($"settingPath{i + 1}", true)[0] as LookUpEdit;
                        LookUpEdit settingPath_iq = this.Controls.Find($"settingPath_iq{i + 1}", true)[0] as LookUpEdit;
                        LookUpEdit settingPath_tve = this.Controls.Find($"settingPath_tve{i + 1}", true)[0] as LookUpEdit;
                        LookUpEdit settingPath_sensor = this.Controls.Find($"settingPath_sensor{i + 1}", true)[0] as LookUpEdit;
                        if (0 != SettingToTve151.SetTips151[i].Setting.Count && 0 != SettingToTve151.SetTips151[i].TveSetting.Count)
                        {
                            settingPath.Properties.DataSource = SettingToTve151.SetTips151[i].Setting;
                            //刷新一下下拉框
                            settingPath.Properties.BeginUpdate();
                            //settingPath.EditValueChanged += new System.EventHandler(this.settingPath1_EditValueChanged);
                            settingPath.ItemIndex = 0;
                            if (null != SettingToTve151.SetTips151[i].IqSetting)
                            {
                                SimpleButton btn_iq = this.Controls.Find($"iqbtn_all_{(i + 1).ToString().PadLeft(2, '0')}", true)[0] as SimpleButton;
                                btn_iq.Visible = true;
                                settingPath_iq.Properties.DataSource = SettingToTve151.SetTips151[i].IqSetting;
                                settingPath.Properties.BeginUpdate();
                                //settingPath.EditValueChanged += new System.EventHandler(this.settingPath_iq1_EditValueChanged);
                                settingPath_iq.ItemIndex = 0;
                            }
                            if (null != SettingToTve151.SetTips151[i].TveSetting)
                            {
                                SimpleButton btn_tve = this.Controls.Find($"tvebtn_all_{(i + 1).ToString().PadLeft(2, '0')}", true)[0] as SimpleButton;
                                btn_tve.Visible = true;
                                settingPath_tve.Properties.DataSource = SettingToTve151.SetTips151[i].TveSetting;
                                settingPath.Properties.BeginUpdate();
                                //settingPath.EditValueChanged += new System.EventHandler(this.settingPath_tve1_EditValueChanged);
                                settingPath_tve.ItemIndex = 0;
                            }
                            if (null != SettingToTve151.SetTips151[i].SensorSetting)
                            {
                                settingPath_sensor.Properties.DataSource = SettingToTve151.SetTips151[i].SensorSetting;
                                settingPath.Properties.BeginUpdate();
                                //settingPath.EditValueChanged += new System.EventHandler(this.settingPath_sensor1_EditValueChanged);
                                settingPath_sensor.ItemIndex = 0;
                            }
                        }
                        //判断有datapath文件缺少TVE文件时
                        else if (0 != SettingToTve151.SetTips151[i].Setting.Count && 0 == SettingToTve151.SetTips151[i].TveSetting.Count)
                        {
                            nulltips += SettingToTve151.SetTips151[i].TransferName + SettingToTve151.SetTips151[i].VideoHex + ",";
                        }
                    }
                    catch (Exception ex)
                    {

                        throw;
                    }
                }
            }
            else
            {
                int noOSD = 1;
                var Settinglist = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("datapath")).ToList();
                var SensorSettinglist = tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("sensor") && !string.IsNullOrEmpty(c.PathName)).ToList();
                var TveSettinglist = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("tve")).ToList();
                var IqSettinglist = tlvList.Where(c => !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("iq_setting")).ToList();
                //Settinglist =  Settinglist.Where(c=>c.StandardName && c.TimingName)
                //过滤掉制式相同时序相同的文件
                //Settinglist = Settinglist.GroupBy(c => new { c.StandardName ,c.TimingName}).Select(group => group.First()) .ToList();
                for (int i = 0; i < Settinglist.Count(); i++)
                {
                    //if (SettingToTve151.SetTips151.Exists(c=>c.))
                    //{

                    //}
                    
                    if (null == Settinglist[i].TimingName || null == Settinglist[i].StandardName)
                    {
                        continue;
                    }
                    var TransferName = Settinglist[i].StandardName.ToLower();
                    var VideoName = Settinglist[i].TimingName.ToLower();
                    if (null != Settinglist[i])
                    {
                        SettingToTve151.SetTips151[i].VideoHex = VideoName;
                        SettingToTve151.SetTips151[i].TransferName = TransferName;
                        SettingToTve151.SetTips151[i].SettingNo = (i + 1).ToString();
                        SettingToTve151.SetTips151[i].Setting = new List<SettingData>();
                        var aa = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("datapath") && c.PathName.ToLower().Contains(Settinglist[i].PathName.ToLower())).ToList();
                        var copy = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("datapath") && c.PathName.ToLower().Contains(Settinglist[i].PathName.ToLower())).ToList();
                        for (int z = 0; z < copy.Count(); z++)
                        {
                            SettingToTve151.SetTips151[i].Setting.Add(new SettingData{FilePath = copy[z].FilePath,FileName = copy[z].FileName});
                        }
                        var t = tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("sensor") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].SensorSetting = new List<SettingData>();
                        copy = tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("sensor") && !string.IsNullOrEmpty(c.PathName) && c.PathName.ToLower().Contains(Settinglist[i].sensorName.ToLower())).ToList();
                        if (TransferName.ToLower() == "cvbs")
                        {
                            switch (Settinglist[i].sensorName)
                            {
                                case "720p60fps":
                                    copy.AddRange(SensorSettinglist.Where(c => c.FileName.ToLower().Contains("sensor") && c.FileName.ToLower().Contains("ntsc") && c.FileName.ToLower().Contains("720p")).ToList());
                                    break;
                                case "720p50fps":
                                    copy.AddRange(SensorSettinglist.Where(c => c.FileName.ToLower().Contains("sensor") && c.FileName.ToLower().Contains("pal") && c.FileName.ToLower().Contains("720p")).ToList());
                                    break;
                                case "960h60fps":
                                    copy.AddRange(SensorSettinglist.Where(c => c.FileName.ToLower().Contains("sensor") && c.FileName.ToLower().Contains("ntsc") && c.FileName.ToLower().Contains("960h")).ToList());
                                    break;
                                case "960h50fps":
                                    copy.AddRange(SensorSettinglist.Where(c => c.FileName.ToLower().Contains("sensor") && c.FileName.ToLower().Contains("pal") && c.FileName.ToLower().Contains("960h")).ToList());
                                    break;
                                default:
                                    break;
                            }
                        }
                        for (int z = 0; z < copy.Count(); z++)
                        {
                            SettingToTve151.SetTips151[i].SensorSetting.Add(new SettingData { FilePath = copy[z].FilePath, FileName = copy[z].FileName });
                        }
                        var t1 = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("tve") && c.PathName.ToLower().Contains(Settinglist[i].PathName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].TveSetting = new List<SettingData>();
                        copy = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("tve") && c.PathName.ToLower().Contains(Settinglist[i].PathName.ToLower())).ToList();
                        for (int z = 0; z < copy.Count(); z++)
                        {
                            SettingToTve151.SetTips151[i].TveSetting.Add(new SettingData { FilePath = copy[z].FilePath, FileName = copy[z].FileName });
                        }
                        SettingToTve151.SetTips151[i].IqSetting = new List<SettingData>();
                        //
                        copy = tlvList.Where(c => !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("iq_setting")).ToList();
                        for (int z = 0; z < copy.Count(); z++)
                        {
                            SettingToTve151.SetTips151[i].IqSetting.Add(new SettingData { FilePath = copy[z].FilePath, FileName = copy[z].FileName });
                        }
                       
                    }
                    else
                    {
                        SettingToTve151.SetTips151[i].Setting = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("datapath") && c.PathName.ToLower().Contains(Settinglist[i].PathName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].SensorSetting = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("sensor") && c.sensorName.ToLower().Contains(Settinglist[i].sensorName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].TveSetting = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("tve") && c.PathName.ToLower().Contains(Settinglist[i].PathName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].IqSetting = tlvList.Where(c => !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("iq_setting")).ToList();
                    }

                    listBin.Add(new BinChoiceData() { tag = i, BinName = $"{ SettingToTve151.SetTips151[i].Setting.Last().PathName}", isShow = true, Sort = i });
                    try
                    {

                        if (0 != SettingToTve151.SetTips151[i].Setting.Count && 0 != SettingToTve151.SetTips151[i].TveSetting.Count)
                        {
                            LookUpEdit settingPath = this.Controls.Find($"settingPath{noOSD}", true)[0] as LookUpEdit;
                            LookUpEdit settingPath_iq = this.Controls.Find($"settingPath_iq{noOSD}", true)[0] as LookUpEdit;
                            LookUpEdit settingPath_tve = this.Controls.Find($"settingPath_tve{noOSD}", true)[0] as LookUpEdit;
                            LookUpEdit settingPath_sensor = this.Controls.Find($"settingPath_sensor{noOSD}", true)[0] as LookUpEdit;

                           
                            
                            

                            noOSD++;
                            settingPath.Properties.DataSource = SettingToTve151.SetTips151[i].Setting;
                            //刷新一下下拉框
                            settingPath.Properties.BeginUpdate();
                            //settingPath.EditValueChanged += new System.EventHandler(this.settingPath1_EditValueChanged);
                            settingPath.ItemIndex = 0;
                            if (null != SettingToTve151.SetTips151[i].IqSetting)
                            {
                                SimpleButton btn_iq = this.Controls.Find($"iqbtn_all_{(noOSD - 1).ToString().PadLeft(2, '0')}", true)[0] as SimpleButton;
                                btn_iq.Visible = true;
                                settingPath_iq.Properties.DataSource = SettingToTve151.SetTips151[i].IqSetting;
                                settingPath.Properties.BeginUpdate();
                                //settingPath.EditValueChanged += new System.EventHandler(this.settingPath_iq1_EditValueChanged);
                                settingPath_iq.ItemIndex = 0;
                            }
                            if (null != SettingToTve151.SetTips151[i].TveSetting)
                            {
                                SimpleButton btn_tve = this.Controls.Find($"tvebtn_all_{(noOSD - 1).ToString().PadLeft(2, '0')}", true)[0] as SimpleButton;
                                btn_tve.Visible = true;
                                settingPath_tve.Properties.DataSource = SettingToTve151.SetTips151[i].TveSetting;
                                settingPath.Properties.BeginUpdate();
                                //settingPath.EditValueChanged += new System.EventHandler(this.settingPath_tve1_EditValueChanged);
                                settingPath_tve.ItemIndex = 0;
                            }
                            if (null != SettingToTve151.SetTips151[i].SensorSetting)
                            {
                                settingPath_sensor.Properties.DataSource = SettingToTve151.SetTips151[i].SensorSetting;
                                settingPath.Properties.BeginUpdate();
                                //settingPath.EditValueChanged += new System.EventHandler(this.settingPath_sensor1_EditValueChanged);
                                settingPath_sensor.ItemIndex = 0;
                            }
                        }
                        //判断有datapath文件缺少TVE文件时
                        else if (0 != SettingToTve151.SetTips151[i].Setting.Count && 0 == SettingToTve151.SetTips151[i].TveSetting.Count)
                        {
                            nulltips += SettingToTve151.SetTips151[i].TransferName + SettingToTve151.SetTips151[i].VideoHex + ",";
                        }
                    }
                    catch (Exception ex)
                    {

                        throw;
                    }
                }
                for (int i = 0; i < SettingToTve151.SetTips151.Count(); i++)
                {
                    var TransferName = SettingToTve151.SetTips151[i].TransferName;
                    var VideoName = SettingToTve151.SetTips151[i].VideoName;




                    //if (VideoName.Contains("5M20")|| VideoName.Contains("5M12"))
                    //{

                    //}
                    if (null == VideoName || null == TransferName)
                    {
                        continue;
                    }
                    if (null != SettingToTve151.SetTips151[i].Setting)
                    {
                        SettingToTve151.SetTips151[i].Setting = new List<SettingData>();
                        var aa = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("datapath") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].Setting.AddRange(tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("datapath") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList());
                        var t = tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("sensor") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].SensorSetting = new List<SettingData>();
                        SettingToTve151.SetTips151[i].SensorSetting.AddRange(tlvList.Where(c => !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("sensor") && !string.IsNullOrEmpty(c.PathName) && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList());
                        var t1 = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("tve") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].TveSetting = new List<SettingData>();
                        SettingToTve151.SetTips151[i].TveSetting.AddRange(tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("tve") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList());
                        SettingToTve151.SetTips151[i].IqSetting = new List<SettingData>();
                        //
                        SettingToTve151.SetTips151[i].IqSetting.AddRange(tlvList.Where(c => !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("iq_setting")).ToList());
                    }
                    else
                    {
                        SettingToTve151.SetTips151[i].Setting = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("datapath") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].SensorSetting = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("sensor") && c.sensorName.ToLower().Contains(VideoName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].TveSetting = tlvList.Where(c => !string.IsNullOrEmpty(c.StandardName) && c.StandardName.ToLower() == TransferName.ToLower() && !string.IsNullOrEmpty(c.PathName) && c.FileName.ToLower().Contains("tve") && c.PathName.ToLower().Contains(VideoName.ToLower())).ToList();
                        SettingToTve151.SetTips151[i].IqSetting = tlvList.Where(c => !string.IsNullOrEmpty(c.FileName) && c.FileName.ToLower().Contains("iq_setting")).ToList();
                    }
                    try
                    {

                        if (0 != SettingToTve151.SetTips151[i].Setting.Count && 0 != SettingToTve151.SetTips151[i].TveSetting.Count)
                        {
                            LookUpEdit settingPath = this.Controls.Find($"settingPath{noOSD}", true)[0] as LookUpEdit;
                            LookUpEdit settingPath_iq = this.Controls.Find($"settingPath_iq{noOSD}", true)[0] as LookUpEdit;
                            LookUpEdit settingPath_tve = this.Controls.Find($"settingPath_tve{noOSD}", true)[0] as LookUpEdit;
                            LookUpEdit settingPath_sensor = this.Controls.Find($"settingPath_sensor{noOSD}", true)[0] as LookUpEdit;
                            noOSD++;
                            settingPath.Properties.DataSource = SettingToTve151.SetTips151[i].Setting;
                            //刷新一下下拉框
                            settingPath.Properties.BeginUpdate();
                            //settingPath.EditValueChanged += new System.EventHandler(this.settingPath1_EditValueChanged);
                            settingPath.ItemIndex = 0;
                            if (null != SettingToTve151.SetTips151[i].IqSetting)
                            {
                                SimpleButton btn_iq = this.Controls.Find($"iqbtn_all_{(noOSD - 1).ToString().PadLeft(2, '0')}", true)[0] as SimpleButton;
                                btn_iq.Visible = true;
                                settingPath_iq.Properties.DataSource = SettingToTve151.SetTips151[i].IqSetting;
                                settingPath.Properties.BeginUpdate();
                                //settingPath.EditValueChanged += new System.EventHandler(this.settingPath_iq1_EditValueChanged);
                                settingPath_iq.ItemIndex = 0;
                            }
                            if (null != SettingToTve151.SetTips151[i].TveSetting)
                            {
                                SimpleButton btn_tve = this.Controls.Find($"tvebtn_all_{(noOSD - 1).ToString().PadLeft(2, '0')}", true)[0] as SimpleButton;
                                btn_tve.Visible = true;
                                settingPath_tve.Properties.DataSource = SettingToTve151.SetTips151[i].TveSetting;
                                settingPath.Properties.BeginUpdate();
                                //settingPath.EditValueChanged += new System.EventHandler(this.settingPath_tve1_EditValueChanged);
                                settingPath_tve.ItemIndex = 0;
                            }
                            if (null != SettingToTve151.SetTips151[i].SensorSetting)
                            {
                                settingPath_sensor.Properties.DataSource = SettingToTve151.SetTips151[i].SensorSetting;
                                settingPath.Properties.BeginUpdate();
                                //settingPath.EditValueChanged += new System.EventHandler(this.settingPath_sensor1_EditValueChanged);
                                settingPath_sensor.ItemIndex = 0;
                            }
                        }
                        //判断有datapath文件缺少TVE文件时
                        else if (0 != SettingToTve151.SetTips151[i].Setting.Count && 0 == SettingToTve151.SetTips151[i].TveSetting.Count)
                        {
                            nulltips += SettingToTve151.SetTips151[i].TransferName + SettingToTve151.SetTips151[i].VideoHex + ",";
                        }
                    }
                    catch (Exception ex)
                    {

                        throw;
                    }
                }
            }
            Thread.Sleep(10);
            //获取到有datapath关键字但无法进行sensor TVE 匹配的文件
            var nulldatapathlist = tlvList.Where(file =>
            file.FileName.Contains("datapath") &&
            (file.StandardName == null || file.TimingName == null || file.sensorName == null))
            .ToList();
            foreach (var item in nulldatapathlist)
            {
                nulldatapath += item.FileName + ",";
            }
            if (!string.IsNullOrEmpty(nulltips) || !string.IsNullOrEmpty(nulldatapath))
            {
                string tipstxt = "";
                if (!string.IsNullOrEmpty(nulltips))
                {
                    tipstxt += "以下制式在文件夹中存在datapath但不存在tve检查过后重新导入：" + nulltips;
                }
                if (!string.IsNullOrEmpty(nulldatapath))
                {
                    tipstxt += "\r\n以下文件存在datapath关键字但无法匹配TVE，sensor请检查文件命名：" + nulldatapath;
                }
                XtraMessageBox.Show(tipstxt);
            }
            
            

        }
        #endregion



        private void commonTxt_EditValueChanged(object sender, EventArgs e)
        {

            if (isRead) return;
           
            if (!string.IsNullOrEmpty(commonTxt.Text) && commonTxt.Text != "请选择文件")
            {
                //id 117  IsModified =1;
                var model99 = Bincurrency_BLL.GetSingle(c => c.GuidId == GuidNo && c.SerialNo == 48 && c.BinId == 7);
                var list = Bincurrency_BLL.GetList(c => c.GuidId == BinModel.GuidId && (c.BinId == 6 || c.BinId == 7 || c.BinId == 8 || c.BinId == 9));
                var modelMax = list.Max(c => c.SortOrder) == null ? 0 : list.Max(c => c.SortOrder);
                if (null == model99)
                {
                    var mode102 = new bincurrency();
                    mode102.GuidId = GuidNo;
                    mode102.BinId = 7;
                    mode102.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    mode102.BinInPath = commonTxt.EditValue.ToString();
                    mode102.BinInName = Path.GetFileName(commonTxt.EditValue.ToString());
                    var pathNameout = Copy_Files_For_Header_Patch_Tool(commonTxt.EditValue.ToString(), true, "", true, false);
                    mode102.BinOutName = Path.GetFileName(pathNameout);
                    mode102.BinOutPath = pathNameout;
                    mode102.SerialNo = 48;
                    mode102.SortOrder = 48;
                    mode102.IsModified = 1;
                    mode102.FileStatus = 2;
                    
                    mode102.LengthAddress = HeaderHelper.FilePathLengthComplementnew(mode102.BinOutPath);
                    Bincurrency_BLL.Insert(mode102);
                }
                else
                {
                    model99.BinInPath = commonTxt.EditValue.ToString();
                    model99.BinInName = Path.GetFileName(commonTxt.EditValue.ToString());
                    var pathNameout = Copy_Files_For_Header_Patch_Tool(commonTxt.EditValue.ToString(), true, "", true, false);
                    model99.BinOutName = Path.GetFileName(pathNameout);
                    model99.BinOutPath = pathNameout;
                    model99.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model99.BinOutPath);
                    model99.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    Bincurrency_BLL.Update(model99);
                }

            }
            else
            {
                Bincurrency_BLL.Deletes(c => c.BinId == 7 && c.GuidId == GuidNo);
            }
        }
        private void ClearLookUpEditDataSource()
        {
            //if (!osdcheck)
            //{
            //    foreach (var item in SettingToTve151.SetTips151)
            //    {
            //        item.Setting = null;
            //        item.IqSetting = null;
            //        item.SensorSetting = null;
            //        item.TveSetting = null;
            //    }
            //}

            //for (int i = 1; i < 48; i++)
            //{
            //    LookUpEdit settingPath = this.Controls.Find($"settingPath{i }", true)[0] as LookUpEdit;
            //    LookUpEdit settingPath_iq = this.Controls.Find($"settingPath_iq{i }", true)[0] as LookUpEdit;
            //    LookUpEdit settingPath_tve = this.Controls.Find($"settingPath_tve{i}", true)[0] as LookUpEdit;
            //    LookUpEdit settingPath_sensor = this.Controls.Find($"settingPath_sensor{i }", true)[0] as LookUpEdit;
            //    settingPath.Properties.DataSource = null; settingPath.EditValue = string.Empty;
            //    settingPath_iq.Properties.DataSource = null; settingPath_iq.EditValue = string.Empty;
            //    settingPath_tve.Properties.DataSource = null; settingPath_tve.EditValue = string.Empty;
            //    settingPath_sensor.Properties.DataSource = null; settingPath_sensor.EditValue = string.Empty;
            //}
            isRead = true;
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            for (int i = 0; i < fieldInfo.Length; i++)
            {
              var cont =  this.Controls.Find(fieldInfo[i].Name, true);

                foreach (var item in cont)
                {
                    if (item is LookUpEdit) {
                       ( item as LookUpEdit).EditValue =null;
                        (item as LookUpEdit).ItemIndex = -1;
                    }

                }
            }
            isRead = false;
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            if (simpleButton4.ImageOptions.ImageUri.Uri.Contains("Stretch"))
            {
                simpleButton4.ImageOptions.ImageUri.Uri = "Squeeze;Size32x32;Colored";
                //previous_32x32.png
                for (int i = 0; i < SettingToTve151.SetTips151.Count(); i++)
                {
                    if (0 == SettingToTve151.SetTips151[i].Setting.Count && 0 == SettingToTve151.SetTips151[i].TveSetting.Count)
                    {
                        Control col = this.Controls.Find($"txtgroup{i + 1}", true)[0];
                        col.Visible = false;
                    }
                }
            }
            else
            {
                simpleButton4.ImageOptions.ImageUri.Uri = "Stretch;Size32x32;Colored";
                //next_32x32.png
                for (int i = 0; i < 48; i++)
                {
                    Control col = this.Controls.Find($"txtgroup{i + 1}", true)[0];
                    col.Visible = true;
                }
            }


        }

        private void btn_polling_Click(object sender, EventArgs e)
        {
            if (isPress_key == 0)
            {//按键
                //XChip_BinChoice xcbc = new XChip_BinChoice(isPress_key, listBin.Where(c => c.isShow == true).ToList());
                //xcbc.StartPosition = FormStartPosition.CenterParent;
                //xcbc.ShowDialog();
                //fuzhi();
            }
            else if (isPress_key == 1)
            {//ADC
                //XChip_ADCPollingForm xchip_adcPForm = new XChip_ADCPollingForm(listBin.Where(c => c.isShow == true).ToList());
                //xchip_adcPForm.StartPosition = FormStartPosition.CenterParent;
                //xchip_adcPForm.ShowDialog();
            }

            if (listBin.Count<=0)
            {
                XtraMessageBox.Show("请先选择文件！");
                return;
            }

            XChip_Polling xpoll = new XChip_Polling(isPress_key,listBin);
            xpoll.StartPosition = FormStartPosition.CenterParent;
            xpoll.SendPolling += Xpoll_SendPolling;
            xpoll.ShowDialog();
        }

        private void Xpoll_SendPolling(string isAdc)
        {
            //获取轮询修改文本内容
            pollintStr = isAdc;
        }

        private void bianhaoLook_EditValueChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var model99 = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo);
            if (!model99.Exists(c => c.BinId == 11 && c.SerialNo == 0 && c.GuidId == GuidNo)) //binid 
            {
                var txtEditValue = Convert.ToUInt32(bianhaoLook.EditValue.ToString(), 10).ToString("X2");
                //if (listBin.Count >= (int)Convert.ToUInt32(bianhaoLook.EditValue.ToString(), 10))
                //{
                //    txtEditValue = listBin[(int)Convert.ToUInt32(bianhaoLook.EditValue.ToString(), 10)].Sort.ToString("X2");
                //}
                var mode102 = new bincurrency();
                mode102.GuidId = GuidNo;
                mode102.BinId = 11;
                mode102.LengthAddress = "1000";
                mode102.BinInName = $"{txtEditValue}.txt";
                mode102.BinInPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\{txtEditValue}.txt";
                mode102.BinOutName = $"{txtEditValue}.txt";
                mode102.BinOutPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\{txtEditValue}.txt";
                mode102.BinAddressNo = bianhaoLook.EditValue.ToString();
                mode102.BinAddressOutName = $"{Application.StartupPath}\\Lib\\XChip_Bin\\{txtEditValue}.txt";
                mode102.SortOrder = 0;
                mode102.SerialNo = 0;
                mode102.IsModified = 0;
                Bincurrency_BLL.Insert(mode102);
            }
            else
            {
                
                var txtEditValue = Convert.ToUInt32(bianhaoLook.EditValue.ToString(), 10).ToString("X2");
                //更新
                var model = model99.First(c => c.BinId == 11 && c.SerialNo == 0 && c.GuidId == GuidNo);
                model.BinInName = $"{txtEditValue}.txt";
                model.BinInPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\{txtEditValue}.txt";
                model.BinOutName = $"{txtEditValue}.txt";
                model.BinOutPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\{txtEditValue}.txt";
                model.BinAddressNo = bianhaoLook.EditValue.ToString();
                model.BinAddressOutName = $"{Application.StartupPath}\\Lib\\XChip_Bin\\{txtEditValue}.txt";
                Bincurrency_BLL.Update(model);
            }
        }
        private void EmptySetTips151()
        {
            foreach (var item in SettingToTve151.SetTips151)
            {
                item.Setting = null;
                item.IqSetting = null;
                item.SensorSetting = null;
                item.TveSetting = null;
                item.CommonSetting = null;
            }
        }
        private void EmptySetTips151File()
        {
            foreach (var item in SettingToTve151.SetTips151)
            {
                foreach (var items in item.Setting)
                {
                    items.FileName = string.Empty;
                    items.FilePath = string.Empty;
                }
                foreach (var items in item.IqSetting)
                {
                    items.FileName = string.Empty;
                    items.FilePath = string.Empty;
                }
                foreach (var items in item.SensorSetting)
                {
                    items.FileName = string.Empty;
                    items.FilePath = string.Empty;
                }
                foreach (var items in item.TveSetting)
                {
                    items.FileName = string.Empty;
                    items.FilePath = string.Empty;
                }
                //item.Setting = null;
                //item.IqSetting = null;
                //item.SensorSetting = null;
                //item.TveSetting = null;
                item.CommonSetting = null;
            }
        }

        private void iqbtn_all_01_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }

            var btn = sender as SimpleButton;
            var noOsd =Convert.ToInt16(btn.Name.Replace("iqbtn_all_", ""));
            //settingPath_iq1
            LookUpEdit settingPath = this.Controls.Find($"settingPath_iq{noOsd}", true)[0] as LookUpEdit;
            string tempTxt = settingPath.Text;
            string path = settingPath.EditValue.ToString();
            if (string.IsNullOrEmpty(path) || path.Contains("请选择"))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($" IQ文件路径 {noOsd} 未选择！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string tempPath = string.Empty;
            if (System.IO.Path.GetDirectoryName(path).Contains("SettingTemp"))
            {
                tempPath = System.IO.Path.GetDirectoryName(path) + "\\";
            }
            else
            {
                tempPath = System.IO.Path.GetDirectoryName(path) + "\\SettingTemp\\";
            }
            string tempName = string.Empty;
            if (Path.GetFileNameWithoutExtension(path).Contains($"_iq_"))
            {
                var t = Path.GetFileNameWithoutExtension(path);
                var end = t.IndexOf($"_iq_");
                tempName = t.Substring(0, end)+ $"_iq_{noOsd}_" + DateTime.Now.ToString("MMddHHmmss");
            }
            else
            {
                tempName = Path.GetFileNameWithoutExtension(path) + $"_iq_{noOsd}_" + DateTime.Now.ToString("MMddHHmmss");
            }
            //确定目录是否存在
            if (!Directory.Exists(tempPath))
            {
                //创建它不存在的目录
                Directory.CreateDirectory(tempPath);
            }

            var pSaveFilePath = $"{tempPath}{tempName}{Path.GetExtension(path)}";

            if (!File.Exists(pSaveFilePath))//必须判断要复制的文件是否存在
            {
                File.Copy(path, pSaveFilePath, true);//三个参数分别是源文件路径，存储路径，若存储路径有相同文件是否替换
            }
            var listStr = File.ReadAllLines(pSaveFilePath);
            string add = "80";//  0xfffd
            string addval = string.Empty; //0xfffe
            string duVal = string.Empty; //读取的值
            for (int i = 0; i < listStr.Count(); i++)
            {
                if (listStr[i].Contains("don't_modify")) //已知的过滤条件 后期可能有添加
                {
                    continue;
                }
                string[] col = listStr[i].Replace('，', ',').Split(',');
                if (col.Count() > 2)
                {
                    string colFirst = col.First().Trim().ToLower();
                    long tempVal = -1;
                    //过滤关键字
                    if (colFirst == "0xffff" || colFirst == "0xfff3" || colFirst == "0xfff6" || colFirst == "0xfff7" || colFirst == "0xfff8" || colFirst == "0xfff9" || colFirst == "0xfffa" || colFirst == "0xfff0" || colFirst == "0xfff1")
                    {
                        continue;
                    }
                    else if (colFirst == "0xfffd")
                    {
                        add = col[1].Replace("0x", "");
                    }
                    else if (colFirst == "0xfffe")
                    {
                        addval = col[1].Replace("0x", "");
                    }
                    else if (colFirst.Contains("0x") && !colFirst.Contains("//"))
                    {
                        string sonVal = colFirst.Replace("0x", "").Replace(" ", "");
                        duVal = (add + addval + sonVal.PadLeft(4, '0')).Replace("0x", "").Replace(" ", "").ToLower();

                        if (duVal.Length != 8 || duVal == "80300000" || duVal == "80300001" || duVal == "80300002" || duVal == "80300003" || duVal == "80300004"
                                    || duVal == "8014062c")
                            continue;

                        tempVal = SerialSend.ReadRegister(Convert.ToUInt32(duVal, 16), sPortTemp);
                        string oldVal = col[1].Replace("0x", "").Replace(" ", "");
                        col[1] = col[1].Replace(oldVal, tempVal.ToString("x2"));
                        listStr[i] = string.Join(",", col);
                    }

                   
                }
            }


            File.WriteAllLines(pSaveFilePath, listStr, Encoding.Default);
            //这里处理选择IQ相同文件的下拉框  同时选择新的更新IQ文件

            for (int j = 1; j < 48; j++)
            {
                //获取所有下拉框
                LookUpEdit settingPathT = this.Controls.Find($"settingPath_iq{j}", true)[0] as LookUpEdit;
                //判断文件选择是否相同
                if (settingPathT.Text == tempTxt)
                {
                    //获取全局存储的IQ 用于新的赋值下拉框
                    var iqList = SettingToTve151.SetTips151[int.Parse(settingPathT.Tag.ToString()) - 1].IqSetting;
                    iqList.ForEach(c => { c.IsChecked = false; });
                    //添加新值，并且选中  赋值
                    iqList.Add(new SettingData()
                    {
                        FilePath = pSaveFilePath,
                        FileName = Path.GetFileName(pSaveFilePath),
                        IsChecked = true
                    });
                    //更新到全局settingIQ
                    SettingToTve151.SetTips151[int.Parse(settingPathT.Tag.ToString()) - 1].IqSetting = iqList;
                    //更新下拉框选中
                    settingPathT.Properties.DataSource = iqList;
                    settingPathT.Properties.BeginUpdate();
                    settingPathT.ItemIndex = iqList.Count() - 1;
                }


            }

        }

        private void tvebtn_all_01_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }

            var btn = sender as SimpleButton;
            //tvebtn_all_01
            var noOsd = Convert.ToInt16(btn.Name.Replace("tvebtn_all_", ""));
            //settingPath_tve1
            LookUpEdit settingPath = this.Controls.Find($"settingPath_tve{noOsd}", true)[0] as LookUpEdit;
            string path = settingPath.EditValue.ToString();
            if (string.IsNullOrEmpty(path) || path.Contains("请选择"))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($" IQ文件路径 {noOsd} 未选择！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string tempPath = string.Empty;
            if (System.IO.Path.GetDirectoryName(path).Contains("SettingTemp"))
            {
                tempPath = System.IO.Path.GetDirectoryName(path) + "\\";
            }
            else
            {
                tempPath = System.IO.Path.GetDirectoryName(path) + "\\SettingTemp\\";
            }
            string tempName = string.Empty;
            if (Path.GetFileNameWithoutExtension(path).Contains($"_tve_"))
            {
                var t = Path.GetFileNameWithoutExtension(path);
                var end = t.IndexOf($"_tve_");
                tempName = t.Substring(0, end) + $"_tve_{noOsd}_" + DateTime.Now.ToString("MMddHHmmss");
            }
            else
            {
                tempName = Path.GetFileNameWithoutExtension(path) + $"_tve_{noOsd}_" + DateTime.Now.ToString("MMddHHmmss");
            }
            //确定目录是否存在
            if (!Directory.Exists(tempPath))
            {
                //创建它不存在的目录
                Directory.CreateDirectory(tempPath);
            }

            var pSaveFilePath = $"{tempPath}{tempName}{Path.GetExtension(path)}";

            if (!File.Exists(pSaveFilePath))//必须判断要复制的文件是否存在
            {
                File.Copy(path, pSaveFilePath, true);//三个参数分别是源文件路径，存储路径，若存储路径有相同文件是否替换
            }
            var listStr = File.ReadAllLines(pSaveFilePath);
            string add = "80";//  0xfffd
            string addval = string.Empty; //0xfffe
            string duVal = string.Empty; //读取的值
            for (int i = 0; i < listStr.Count(); i++)
            {
                if (listStr[i].Contains("don't_modify")) //已知的过滤条件 后期可能有添加
                {
                    continue;
                }
                string[] col = listStr[i].Replace('，', ',').Split(',');
                if (col.Count() > 2)
                {
                    string colFirst = col.First().Trim().ToLower();
                    long tempVal = -1;
                    //过滤关键字
                    if (colFirst == "0xffff" || colFirst == "0xfff3" || colFirst == "0xfff6" || colFirst == "0xfff7" || colFirst == "0xfff8" || colFirst == "0xfff9" || colFirst == "0xfffa" || colFirst == "0xfff0" || colFirst == "0xfff1")
                    {
                        continue;
                    }
                    else if (colFirst == "0xfffd")
                    {
                        add = col[1].Replace("0x", "");
                    }
                    else if (colFirst == "0xfffe")
                    {
                        addval = col[1].Replace("0x", "");
                    }
                    else if (colFirst.Contains("0x") && !colFirst.Contains("//"))
                    {
                        string sonVal = colFirst.Replace("0x", "").Replace(" ", "");
                        duVal = (add + addval + sonVal.PadLeft(4, '0')).Replace("0x", "").Replace(" ", "").ToLower();

                        if (duVal.Length != 8 || duVal == "80300000" || duVal == "80300001" || duVal == "80300002" || duVal == "80300003" || duVal == "80300004"
                                    || duVal == "8014062c")
                            continue;

                        tempVal = SerialSend.ReadRegister(Convert.ToUInt32(duVal, 16), sPortTemp);
                        string oldVal = col[1].Replace("0x", "").Replace(" ", "");
                        col[1] = col[1].Replace(oldVal, tempVal.ToString("x2"));
                        listStr[i] = string.Join(",", col);
                    }


                }
            }


            File.WriteAllLines(pSaveFilePath, listStr, Encoding.Default);
            //这里处理选择IQ相同文件的下拉框  同时选择新的更新IQ文件

            for (int j = 1; j < 48; j++)
            {
                //获取所有下拉框  settingPath_tve1
                LookUpEdit settingPathT = this.Controls.Find($"settingPath_tve{j}", true)[0] as LookUpEdit;
                //判断文件选择是否相同
                if (settingPathT.Text == settingPath.Text)
                {
                    //获取全局存储的IQ 用于新的赋值下拉框
                    var iqList = SettingToTve151.SetTips151[int.Parse(settingPathT.Tag.ToString()) - 1].IqSetting;
                    iqList.ForEach(c => { c.IsChecked = false; });
                    //添加新值，并且选中  赋值
                    iqList.Add(new SettingData()
                    {
                        FilePath = pSaveFilePath,
                        FileName = Path.GetFileName(pSaveFilePath),
                        IsChecked = true
                    });
                    //更新到全局settingIQ
                    SettingToTve151.SetTips151[int.Parse(settingPathT.Tag.ToString()) - 1].IqSetting = iqList;
                    //更新下拉框选中
                    settingPathT.Properties.DataSource = iqList;
                    settingPathT.Properties.BeginUpdate();
                    settingPathT.ItemIndex = iqList.Count() - 1;
                }


            }

        }
       
        private void simpleButton5_Click(object sender, EventArgs e)
        {
            var btn = sender as SimpleButton;

            string path = commonTxt.EditValue.ToString();
            if (string.IsNullOrEmpty(path) || path.Contains("请选择"))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($" IQ文件路径 common 未选择！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string tempPath = string.Empty;
            if (System.IO.Path.GetDirectoryName(path).Contains("SettingTemp"))
            {
                tempPath = System.IO.Path.GetDirectoryName(path) + "\\";
            }
            else
            {
                tempPath = System.IO.Path.GetDirectoryName(path) + "\\SettingTemp\\";
            }
            string tempName = string.Empty;
            if (Path.GetFileNameWithoutExtension(path).Contains($"_commonT_"))
            {
                var t = Path.GetFileNameWithoutExtension(path);
                var end = t.IndexOf($"_commonT_");
                tempName = t.Substring(0, end) + $"_commonT_" + DateTime.Now.ToString("MMddHHmmss");
            }
            else
            {
                tempName = Path.GetFileNameWithoutExtension(path) + $"_commonT_" + DateTime.Now.ToString("MMddHHmmss");
            }
            //确定目录是否存在
            if (!Directory.Exists(tempPath))
            {
                //创建它不存在的目录
                Directory.CreateDirectory(tempPath);
            }

            var pSaveFilePath = $"{tempPath}{tempName}{Path.GetExtension(path)}";

            if (!File.Exists(pSaveFilePath))//必须判断要复制的文件是否存在
            {
                File.Copy(path, pSaveFilePath, true);//三个参数分别是源文件路径，存储路径，若存储路径有相同文件是否替换
            }

            var listStr = File.ReadAllLines(pSaveFilePath);
            string add = "80";//  0xfffd
            string addval = string.Empty; //0xfffe
            string duVal = string.Empty; //读取的值
            for (int i = 0; i < listStr.Count(); i++)
            {
                if (listStr[i].Contains("don't_modify")) //已知的过滤条件 后期可能有添加
                {
                    continue;
                }
                string[] col = listStr[i].Replace('，', ',').Split(',');
                if (col.Count() > 2)
                {
                    string colFirst = col.First().Trim().ToLower();
                    long tempVal = -1;
                    //过滤关键字
                    if (colFirst == "0xffff" || colFirst == "0xfff3" || colFirst == "0xfff6" || colFirst == "0xfff7" || colFirst == "0xfff8" || colFirst == "0xfff9" || colFirst == "0xfffa" || colFirst == "0xfff0" || colFirst == "0xfff1")
                    {
                        continue;
                    }
                    else if (colFirst == "0xfffd")
                    {
                        add = col[1].Replace("0x", "");
                    }
                    else if (colFirst == "0xfffe")
                    {
                        addval = col[1].Replace("0x", "");
                    }
                    else if (colFirst.Contains("0x") && !colFirst.Contains("//"))
                    {
                        string sonVal = colFirst.Replace("0x", "").Replace(" ", "");
                        duVal = (add + addval + sonVal.PadLeft(4, '0')).Replace("0x", "").Replace(" ", "").ToLower();

                        if (duVal.Length != 8 || duVal == "80300000" || duVal == "80300001" || duVal == "80300002" || duVal == "80300003" || duVal == "80300004"
                                    || duVal == "8014062c")
                            continue;

                        tempVal = SerialSend.ReadRegister(Convert.ToUInt32(duVal, 16), sPortTemp);
                        string oldVal = col[1].Replace("0x", "").Replace(" ", "");
                        col[1] = col[1].Replace(oldVal, tempVal.ToString("x2"));
                        listStr[i] = string.Join(",", col);
                    }


                }
            }


            File.WriteAllLines(pSaveFilePath, listStr, Encoding.Default);
            //commonTxt.Properties.DataSource = new List<SettingData> { new SettingData { FilePath = model99.BinInPath, FileName = model99.BinInName } };
            List<SettingData> commonList = new List<SettingData>();
            if (commonTxt.Properties.DataSource is List<SettingData>)
            {
                List<SettingData> list = commonTxt.Properties.DataSource as List<SettingData>;
                commonList.AddRange(list);
            }
            commonList.Add(new SettingData
            {
                FilePath = pSaveFilePath,
                FileName = Path.GetFileName(pSaveFilePath)
            });

            commonTxt.Properties.DataSource = commonList;
            commonTxt.Properties.BeginUpdate();
            commonTxt.ItemIndex = commonList.Count() - 1;
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(threadPro);
            thread.Start();
        }
        private void threadPro()
        {
            MethodInvoker methodInvoker = new MethodInvoker(ShowFormB);

            BeginInvoke(methodInvoker);

        }
        private void ShowFormB()
        {
            //string str = "\t      \t 将图像划分为8x8的区域块，通过特定的矩阵调节lens shading和color shading的补偿增益值,G 通道主要调整校正图像四周与中心的亮度差异，B通道和R 通道主要调整校正图像的色偏，取值范围均为 0x00~0x3f。\r\n"
            //   + "\t      \t 更多详见《调试工具用户手册》。";
            string str = "\t      \t 以AHD P制中1080pScale720为例，\r\n setting中命名规格如下：datapath_setting：datapath_AHD720p25fps_1080pScale720p_setting_xx(xx可自定义) \r\n TVE_setting：TVE_AHD720p25fps_setting_xx(xx可自定义)\r\n common_setting：common_setting_xx(xx可自定义)\r\nsensor_setting：sensor_1080p25fps_setting_xx(xx可自定义)\r\nIQ_setting：IQ_setting_xx(xx可自定义)";
            XChip_OptimizationTips ot = new XChip_OptimizationTips("Setting命名中关键字示例", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();

        }
    }
}